package util;

import com.alibaba.fastjson.JSON;
import pojo.ColDesc;
import pojo.TableDesc;

import java.sql.*;
import java.util.*;

/**
 * @author Administrator
 */
public class JdbcUtil {

    public static Connection getConnection() throws Exception {
        Properties properties = ConfigUtil.getConfig();
        System.out.println("config = " + JSON.toJSON(properties));

        Class.forName("com.mysql.jdbc.Driver");
        String jdbc = "jdbc:mysql://_IP_:_PORT_/_BASENAME_?user=_USERNAME_&password=_PASSWORD_&useUnicode=true&characterEncoding=UTF-8&allowMultiQueries=true&useSSL=false";

        jdbc = jdbc.replace("_IP_", properties.getProperty("ip"))
                .replace("_PORT_", properties.getProperty("port"))
                .replace("_BASENAME_", properties.getProperty("basename"))
                .replace("_USERNAME_", properties.getProperty("username"))
                .replace("_PASSWORD_", properties.getProperty("password"));

        return DriverManager.getConnection(jdbc);
    }

    public static Map<String, String> getTables(Connection conn) throws SQLException {
        Map<String, String> resultMap = new HashMap<>();

        String sql = " SELECT TABLE_NAME, TABLE_COMMENT FROM information_schema.TABLES WHERE table_type='BASE TABLE'";
        PreparedStatement pstmt = conn.prepareStatement(sql);
        ResultSet rs = pstmt.executeQuery();
        while (rs.next()) {
            String tableName = rs.getString("TABLE_NAME");
            String tableComment = rs.getString("TABLE_COMMENT");
            resultMap.put(tableName, tableComment);
        }

        return resultMap;
    }

    public static List<TableDesc> queryTableDescs() throws Exception {
        Connection conn = JdbcUtil.getConnection();
        Map<String, String> tableMaps = JdbcUtil.getTables(conn);
        List<TableDesc> tableDescList = JdbcUtil.queryTableDescs(conn, tableMaps);
        conn.close();
        return tableDescList;
    }

    public static List<TableDesc> queryTableDescs(Connection connection, Map<String, String> tableMaps) throws Exception {
        List<TableDesc> tableDescs = new ArrayList<>();
        DatabaseMetaData metaData = connection.getMetaData();
        tableMaps.entrySet().forEach(entity -> {
            try {
                ResultSet rs = metaData.getColumns(null, "%", entity.getKey(), "%");
                TableDesc tableDesc = new TableDesc(entity.getKey(), entity.getValue());
                while (rs.next()) {
                    // 字段英文
                    String COLUMN_NAME = rs.getString("COLUMN_NAME");
                    // 字段中文
                    String REMARKS = rs.getString("REMARKS");
                    // 字段类型
                    String TYPE_NAME = rs.getString("TYPE_NAME");
                    // 字段长度
                    Integer TYPE_SIZE = rs.getInt("COLUMN_SIZE");
                    // 小数长度
                    Integer DECIMAL_DIGITS = rs.getInt("DECIMAL_DIGITS");
                    // 是否非空 0 = 非空 , 1 = 可为空
                    Integer NULLABLE = rs.getInt("NULLABLE");
                    // 兼容bug
                    if ("BIGINT".equals(TYPE_NAME) && TYPE_SIZE == 19) {
                        TYPE_SIZE = 20;
                    }
                    ColDesc colDesc = new ColDesc(COLUMN_NAME, REMARKS, TYPE_NAME, TYPE_SIZE, DECIMAL_DIGITS, NULLABLE);
                    tableDesc.getColDescs().add(colDesc);
                }
                tableDescs.add(tableDesc);
            } catch (Exception ee) {
                ee.printStackTrace();
            }
        });

        return tableDescs;
    }

}
